package com.chen.cloudpicture.aop;

import com.chen.cloudpicture.annotation.AuthCheck;
import com.chen.cloudpicture.exception.BusinessException;
import com.chen.cloudpicture.exception.ErrorCode;
import com.chen.cloudpicture.model.entity.User;
import com.chen.cloudpicture.model.enums.UserRoleEnum;
import com.chen.cloudpicture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 执行拦截
     */
    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        // 拿到注解里要求的角色属性
        String mustRole = authCheck.mustRole();
        /**
         * 每个请求由一个线程处理，RequestContextHolder利用ThreadLocal机制存储当前线程的请求上下文信息
         * currentRequestAttributes()获得当前请求的各项属性
         * 我们现在用的是tomcat服务器的servlet容器，所以要把请求属性转成servlet子类
         * servlet可提供对http请求和访问的响应
         * HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
         */
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum enumByValue = UserRoleEnum.getEnumByValue(mustRole);
        // 如果不需要权限，放行
        if( enumByValue == null) {
            return joinPoint.proceed();
        }
        // 未登录，不通过
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        if( userRoleEnum == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 现在只有普通用户和管理员，所以只校验管理员
        if (UserRoleEnum.ADMIN.equals(enumByValue) && !UserRoleEnum.ADMIN.equals(userRoleEnum)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 通过权限校验，放行
        return joinPoint.proceed();
    }
}
